<?php
$failed = false;
if ($_POST){
	if (empty($_POST['userName'])||empty($_POST['password'])){
		$failed = true;
	} else {
	  require_once('library.php');
	  // Check user credentials
	  try {
		  $auth = Zend_Auth::getInstance();
		  $adapter = new Zend_Auth_Adapter_DbTable($dbRead,'users','userName','password','sha1(?)');
		  $adapter->setIdentity($_POST['userName']);
		  $adapter->setCredential($_POST['password']);
		  $result = $auth->authenticate($adapter);
		  if ($result->isValid()){
			  $storage = $auth->getStorage();
			  $storage->write($adapter->getResultRowObject(array('userName','firstName','lastName','accessLevel','accountId')));
			  session_start();
			  $sql = "SELECT accountId FROM users WHERE userName =?";
			  $_SESSION['accountId'] = $dbRead->fetchOne($sql,$_POST['userName']);
			  header('location: DBList.php');
			  exit;
		  } else {
			  $failed = true;
		  }
	  } catch (Exception $e) {
		  echo $e->getMessage();
	  }
	}
}
if (isset($_GET['logout'])){
	require_once('library.php');
	try{
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
	} catch (Exception $e) {
		echo $e->getMessage();
	}
}